<template>
  <div class="app-container">
    <el-row :gutter="20" class="toolbar" type="flex" justify="space-between">
      <!-- 右侧按钮 -->
      <el-col :span="25" class="text-right">
        <el-button type="primary" @click="handleCreate">添加路由</el-button>
      </el-col>
    </el-row>
    <!-- 数据表格 -->
    <el-table
        :data="routeList"
        border
        stripe
        style="width: 100%"
        class="data-table">
      <el-table-column
          type="index"
          label="序号"
          width="60"
          align="center">
      </el-table-column>

      <el-table-column
          prop="id"
          label="路由di"
          min-width="120">
      </el-table-column>

      <el-table-column
          prop="uri"
          label="路由地址"
          min-width="150">
      </el-table-column>

      <el-table-column
          prop="path"
          label="路由路径"
          min-width="150">
      </el-table-column>

      <el-table-column
          label="操作"
          width="200"
          align="center">
        <template #default="{row}">
          <el-button
              type="text"
              size="small"
              @click="handleConfig(row)">配置
          </el-button>
          <el-button
              type="text"
              size="small"
              style="color: #ff4d4f"
              @click="handleDelete(row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增创建应用对话框 -->
    <el-dialog
        :title="isAdd ? '添加路由':'配置路由'"
        :visible.sync="createDialogVisible"
        width="600px"
        @close="handleDialogClose">
      <el-form
          :model="createForm"
          :rules="formRules"
          ref="createForm"
          label-position="right"
          label-width="100px">

        <el-form-item label="路由id" prop="id">
          <el-input
              v-model="createForm.id"
              placeholder="请输入路由id，自定义"
              maxlength="20"
              :disabled="!isAdd"
              show-word-limit
              clearable></el-input>
        </el-form-item>

        <el-form-item label="路由地址" prop="uri">
          <el-input
              v-model="createForm.uri"
              placeholder="请输入路由地址，如http://10.1.1.1:8888"
              maxlength="100"
              show-word-limit
              clearable></el-input>
        </el-form-item>

        <el-form-item label="路由路径" prop="path">
          <el-input
              v-model="createForm.path"
              placeholder="请输入路由路径，如/demo/**"
              maxlength="100"
              show-word-limit
              clearable></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="createDialogVisible = false">取 消</el-button>
        <el-button
            type="primary"
            :loading="createLoading"
            @click="handleCreateSubmit">确 定
        </el-button>
      </div>
    </el-dialog>

  </div>

</template>

<script>
import {queryRouteList, createRoute, delRoute, updateRoute} from '@/api/gateway-config'

export default {
  data() {
    return {
      selectedApp: '',
      searchKey: '',
      routeList: [],
      // 新增数据项
      createDialogVisible: false,
      createLoading: false,
      createForm: {
        path: "",
        uri: "",
        id: ""
      },
      isAdd: false,
      formRules: {
        id: [
          {required: true, message: '路由id不能为空', trigger: 'blur'},
          {min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur'}
        ],
        uri: [
          {required: true, message: '路由地址不能为空', trigger: 'blur'},
          {min: 2, max: 100, message: '长度在2到100个字符', trigger: 'blur'}
        ],
        path: [
          {required: true, message: '路由路径不能为空', trigger: 'blur'},
          {min: 2, max: 100, message: '长度在2到100个字符', trigger: 'blur'}
        ]
      },
      detailDialogVisible: false,
    }
  },
  mounted() {
    this.loadAppData()
  },
  methods: {
    // 加载数据方法
    async loadAppData() {
      try {
        const {data} = await queryRouteList()
        this.routeList = data
      } catch (error) {
        console.error('数据加载失败:', error)
      }
    },

    // 修改后的处理方法
    handleSearch() {
      this.loadAppData()
    },
    handleSizeChange() {
      this.loadAppData()
    },
    // 修改后的创建方法
    handleCreate() {
      this.createDialogVisible = true
      this.isAdd = true
      this.createForm.uri = ""
      this.createForm.path = ""
      this.createForm.id = ""
    },
    // 新增方法
    handleDialogClose() {
      this.$refs.createForm.resetFields()
    },
    async handleCreateSubmit() {
      try {
        const valid = await this.$refs.createForm.validate()
        if (!valid) return

        this.createLoading = true
        if (this.isAdd) {
          const response = await createRoute({
            id: this.createForm.id,
            uri: this.createForm.uri,
            path: this.createForm.path
          });
        } else {
          const response = await updateRoute({
            id: this.createForm.id,
            uri: this.createForm.uri,
            path: this.createForm.path
          });
        }
        this.$message.success('操作成功！')
        // 刷新表格数据
        this.loadAppData()
        this.createDialogVisible = false
        this.$refs.createForm.resetFields()
      } catch (error) {
        console.error('操作失败:', error)
      } finally {
        this.createLoading = false
      }
    },
    async handleConfig(row) {
      this.createForm.uri = row.uri
      this.createForm.path = row.path
      this.createForm.id = row.id
      this.createDialogVisible = true
      this.isAdd = false
    },
    handleDelete(row) {
      this.$confirm(`是否删除路由 ${row.id}？`, '确认操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await delRoute({id: row.id})
          this.$message.success(`删除成功`);
          await this.loadAppData()
        } catch (error) {

        }
      }).catch(() => {
        this.$message.info('操作已取消');
      });
    },
  }
}
</script>

<style scoped>

/* 新增样式 */
.el-dialog__body {
  padding: 20px 30px;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-textarea {
  resize: vertical;
}

.toolbar {
  margin-bottom: 20px;
}

.search-input {
  margin-right: 10px;
}

.data-table {
  margin-top: 15px;
}


.text-right {
  text-align: right;
}

.detail-dialog .el-form-item {
  margin-bottom: 15px;
}

.detail-dialog .el-form-item span {
  font-weight: bold;
  color: #333;
}

.detail-dialog .dialog-footer {
  text-align: right;
  padding: 10px 0;
}

.detail-dialog .el-dialog__body {
  padding: 20px 30px;
  background-color: #f9f9f9;
  border-radius: 8px;
}
</style>